#!/usr/bin/env python3
"""
简化版API连接器 - 核心功能演示
"""

import json
from typing import Dict, Any, List, Optional

class SimpleAPIConfigManager:
    """简化版API配置管理器"""
    
    def __init__(self):
        # 静态配置示例
        self.config_data = {
            "apis": {
                "static_data": {
                    "name": "静态数据API",
                    "description": "演示用的静态数据API",
                    "enabled": True,
                    "base_url": "http://localhost",
                    "auth_type": "none",
                    "endpoints": {
                        "get_users": {
                            "path": "/users",
                            "method": "GET",
                            "description": "获取用户列表"
                        },
                        "get_posts": {
                            "path": "/posts",
                            "method": "GET",
                            "description": "获取文章列表"
                        }
                    }
                }
            }
        }
    
    def get_api_config(self, api_name: str) -> Optional[Dict[str, Any]]:
        """获取指定API的配置"""
        apis = self.config_data.get("apis", {})
        if api_name not in apis:
            return None
        
        config = apis[api_name].copy()
        if not config.get("enabled", True):
            return None
        
        return config

class SimpleAPIConnector:
    """简化版API连接器"""
    
    def __init__(self, config: Dict[str, Any]):
        self.config = config
        # 静态数据示例
        self.static_data = {
            "users": [
                {"id": 1, "name": "张三", "email": "zhangsan@example.com"},
                {"id": 2, "name": "李四", "email": "lisi@example.com"},
                {"id": 3, "name": "王五", "email": "wangwu@example.com"}
            ],
            "posts": [
                {"id": 1, "title": "第一篇文章", "content": "这是第一篇文章的内容", "userId": 1},
                {"id": 2, "title": "第二篇文章", "content": "这是第二篇文章的内容", "userId": 2},
                {"id": 3, "title": "第三篇文章", "content": "这是第三篇文章的内容", "userId": 1}
            ]
        }
    
    def call_api(self, endpoint_name: str, params: Dict[str, Any] = None) -> tuple[bool, str, Any]:
        """调用API端点"""
        try:
            # 获取端点配置
            endpoints = self.config.get("endpoints", {})
            if endpoint_name not in endpoints:
                return False, f"端点不存在: {endpoint_name}", None
            
            # 根据端点名称返回静态数据
            if endpoint_name == "get_users":
                return True, "获取用户列表成功", self.static_data["users"]
            elif endpoint_name == "get_posts":
                return True, "获取文章列表成功", self.static_data["posts"]
            else:
                return False, f"未实现的端点: {endpoint_name}", None
        
        except Exception as e:
            return False, f"API调用异常: {str(e)}", None

class SimpleDataStorage:
    """简化版数据存储"""
    
    def __init__(self):
        self.storage = {}
    
    def store_data(self, session_name: str, data: Any) -> tuple[bool, str]:
        """存储数据"""
        try:
            self.storage[session_name] = data
            return True, f"数据已存储到会话: {session_name}"
        except Exception as e:
            return False, f"数据存储失败: {str(e)}"
    
    def get_data(self, session_name: str) -> tuple[bool, Any, str]:
        """获取存储的数据"""
        try:
            if session_name not in self.storage:
                return False, None, f"会话不存在: {session_name}"
            
            return True, self.storage[session_name], "数据获取成功"
        except Exception as e:
            return False, None, f"数据获取失败: {str(e)}"

def main():
    """主函数 - 演示核心功能"""
    print("🚀 简化版API连接器演示")
    print("=" * 40)
    
    # 1. 初始化配置管理器
    config_manager = SimpleAPIConfigManager()
    print("✅ 配置管理器初始化完成")
    
    # 2. 获取API配置
    api_config = config_manager.get_api_config("static_data")
    if not api_config:
        print("❌ 无法获取API配置")
        return
    
    print("✅ API配置加载成功")
    
    # 3. 初始化API连接器
    connector = SimpleAPIConnector(api_config)
    print("✅ API连接器初始化完成")
    
    # 4. 初始化数据存储
    storage = SimpleDataStorage()
    print("✅ 数据存储初始化完成")
    
    # 5. 调用API获取用户数据
    print("\n📡 调用API获取用户数据...")
    success, message, users_data = connector.call_api("get_users")
    if success:
        print(f"✅ {message}")
        print("用户数据:")
        for user in users_data:
            print(f"  - ID: {user['id']}, 姓名: {user['name']}, 邮箱: {user['email']}")
        
        # 存储用户数据
        storage_success, storage_message = storage.store_data("users_session", users_data)
        if storage_success:
            print(f"✅ {storage_message}")
        else:
            print(f"❌ {storage_message}")
    else:
        print(f"❌ {message}")
    
    # 6. 调用API获取文章数据
    print("\n📡 调用API获取文章数据...")
    success, message, posts_data = connector.call_api("get_posts")
    if success:
        print(f"✅ {message}")
        print("文章数据:")
        for post in posts_data:
            print(f"  - ID: {post['id']}, 标题: {post['title']}, 用户ID: {post['userId']}")
        
        # 存储文章数据
        storage_success, storage_message = storage.store_data("posts_session", posts_data)
        if storage_success:
            print(f"✅ {storage_message}")
        else:
            print(f"❌ {storage_message}")
    else:
        print(f"❌ {message}")
    
    # 7. 从存储中获取数据
    print("\n📂 从存储中获取用户数据...")
    storage_success, stored_users, storage_message = storage.get_data("users_session")
    if storage_success:
        print(f"✅ {storage_message}")
        print("存储的用户数据:")
        for user in stored_users:
            print(f"  - ID: {user['id']}, 姓名: {user['name']}, 邮箱: {user['email']}")
    else:
        print(f"❌ {storage_message}")
    
    print("\n🎉 演示完成!")

if __name__ == "__main__":
    print("------>>>在【最小demo】基础上,添加了【配置管理器】+【API连接器】+【数据存储】!")
    main()